package com.umeox.sdk_ring.core

import com.umeox.sdk_ring.UMRingSdk
import com.umeox.sdk_ring.protocol.IAppProtocol
import java.lang.StringBuilder
import java.text.SimpleDateFormat
import java.util.*

/**
 * 戒指指令解析器
 */
class RingCommandParser(private val appProtocolImpl: IAppProtocol) {

    companion object {

        private const val TAG = "RingCommandParser"

        /**
         * 根据下标解析设备语言归属
         */
        fun parseDeviceLanguage(languageType: Int) = when (languageType) {
            0 -> "阿拉伯语"
            1 -> "英语"
            2 -> "法语"
            3 -> "乌尔都语"
            4 -> "土耳其语"
            5 -> "简体中文"
            6 -> "印度尼西亚语"
            7 -> "印地语"
            8 -> "波斯语"
            9 -> "德语"
            10 -> "泰语"
            11 -> "俄语"
            12 -> "马来语"
            else -> "未知语言下标"
        }
    }

    /**
     * 处理消息
     */
    fun handlerReceiveResult(result: String) {
        val isQ = result.startsWith("Q")
        val isR = result.startsWith("R")
        if (!isQ && !isR) {
            return
        }
        UMRingSdk.log(TAG, "收到指令：$result")
        when (result.substring(0, 3)) {
            //时间请求同步： Q01
            "Q01" -> {
                appProtocolImpl.onTimeSyncCallback()
            }
            //设备端主动请求时间同步：R01
            "R01" -> {
                appProtocolImpl.requestTimeSync()
            }
            //上发电量：Q02,充电状态值,电量值,内部版本号,版本编译时间,电压值(供测试用),版本名
            "Q02" -> {
                val strArray = result.split(",")
                val status = strArray[1]
                val bat = strArray[2]
                val version = strArray[3]
                val buildDateTime = strArray[4]
                val voltage = strArray[5]
                val versionName = if (strArray.size > 6) {
                    strArray[6]
                } else {
                    version
                }

                UMRingSdk.log(
                    TAG,
                    "解析结果：\n" + "充电状态：${parseBatteryStatus(status)} \n" + "电量值:$bat \n" + "内部版本号:$version \n" + "版本编译时间:$buildDateTime \n" + "电压值:$voltage \n" + "版本名:$versionName ---"
                )
                appProtocolImpl.onBatteryPowerCallback(
                    status, bat, version, versionName, buildDateTime
                )
            }
            //上发计数信息： Q06,开始时间，结束时间，计数值，tick值
            "Q06" -> {
                val startTime = convertDateTimeFormat(
                    result.split(",")[1],
                    SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH),
                    SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
                )
                val endTime = convertDateTimeFormat(
                    result.split(",")[2],
                    SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH),
                    SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
                )
                val num = result.split(",")[3].toInt()
                val tick = result.split(",")[4]
                val endFlag = result.split(",")[5].toInt()

                UMRingSdk.log(
                    TAG,
                    "解析结果：\n" + "开始时间：$startTime \n" + "结束时间:$endTime \n" + "数量:$num \n" + "tick值:$tick \n" + "结束标志:$endFlag ---"
                )
                appProtocolImpl.onCacheDataCallback(startTime, endTime, num, tick, endFlag)
            }
            //反转收到： Q03
            "Q03" -> {
                val strList = result.split(",")
                //0:正；1:反
                val isPositive = (strList[1] == "0")

                UMRingSdk.log(TAG, "解析结果：屏幕方向：${parsePositive(isPositive)}")
                appProtocolImpl.onScreenFlipCallback(isPositive)
            }
            //寻找设备找到： Q04
            "Q04" -> {
                appProtocolImpl.onDeviceFind()
            }
            //上发设备状态信息： Q05,充电状态值
            "Q05" -> {
                appProtocolImpl.onBatteryPowerChangeCallback()
            }
            //实时计数数据上传：Q07,计数值，tick值
            "Q07" -> {
                val split = result.split(",")
                val num = split[1].toInt()

                var tick = ""
                if (split.size >= 3) {
                    tick = split[2]
                }

                var taskStatus = -1
                if (split.size >= 4) {
                    taskStatus = split[3].toInt()
                }

                var currentTaskNumber = -1
                if (split.size >= 5) {
                    currentTaskNumber = split[4].toInt()
                }

                UMRingSdk.log(
                    TAG,
                    "解析结果：实时数量：$num  tick值：$tick 任务状态：$taskStatus  当前任务计数值:$currentTaskNumber"
                )
                appProtocolImpl.onRealTimeCountCallback(num, tick, taskStatus, currentTaskNumber)
            }
            //关机状态：Q08
            "Q08" -> {
                appProtocolImpl.onShutdownCallback()
            }
            //祈祷设置：Q09
            "Q09" -> {
                appProtocolImpl.onSettingPrayerRemindersCallback()
            }
            //诵经提醒设置：Q11,时间段
            "Q11" -> {
                appProtocolImpl.onChantingRemindersSettingCallback()
            }
            //未传数据条数：Q12
            "Q12" -> {
                val split = result.split(",")
                val num = split[1].toInt()
                //当前实时计数值
                var currentRealTimeNumber = 0
                if (split.size >= 3) {
                    currentRealTimeNumber = split[2].toInt()
                }

                //当前任务实时计数值
                var currentTaskNumber: Int = -1
                if (split.size >= 4) {
                    currentTaskNumber = split[3].toInt()
                }

                appProtocolImpl.onDataCacheSizeCallback(
                    num, currentRealTimeNumber, currentTaskNumber
                )
            }
            //戒指设置项 Q13,屏设置,祈祷设置,诵经设置，亮度设置，语言设置
            // v2:Q13,屏设置,祈祷设置,诵经设置,亮度设置,语言设置,任务功能支持状态
            "Q13" -> {
                val strList = result.split(",")
                //屏设置：(0:正；1:反)
                val isPositive = (strList[1] == "0")
                //祈祷设置：开关#开始时间(不设置：0#0)
                val isOpenPray = strList[2].split("#")[0].toInt()
                //诵经设置：时间间隔(分钟)#时间范围(不设置:0#0#0)
                val timeInterval = strList[3].split("#")[0].toInt()

                var chartingStartTime = ""
                var chartingEndTime = ""
                if (timeInterval != 0) {
                    chartingStartTime = strList[3].split("#")[1]
                    chartingEndTime = strList[3].split("#")[2]

                    if (chartingStartTime.contains("255")) {
                        chartingStartTime = ""
                    }

                    if (chartingEndTime.contains("255")) {
                        chartingEndTime = ""
                    }
                }

                //亮度设置
                val light = strList[4].toInt()
                //语言设置
                val languageType = strList[5].toInt()

                var taskSupport = false
                if (strList.size >= 7) {
                    taskSupport = strList[6].toInt() == 1
                }

                var taskStatus = -1
                if (strList.size >= 8) {
                    taskStatus = strList[7].toInt()
                }

                var targetNumber = -1
                if (strList.size >= 9) {
                    targetNumber = strList[8].toInt()
                }

                var taskId = -1
                if (strList.size >= 10) {
                    taskId = strList[9].toInt()
                }
                var remarks = ""
                if (strList.size >= 11) {
                    remarks = strList[10]
                }
                var protocolVersion = ""
                if (strList.size >= 12) {
                    protocolVersion = strList[11]
                }

                UMRingSdk.log(
                    TAG,
                    "解析结果：设备配置：\n" + "屏幕方向： ${parsePositive(isPositive)} \n" + "礼拜提醒状态： ${
                        parseSalahRemindStatus(isOpenPray)
                    } \n" + "赞念提醒状态： ${parseDhikrRemindStatus(timeInterval)} \n" + "赞念提醒开始时间： $chartingStartTime \n" + "赞念提醒结束时间： $chartingEndTime \n" + "亮度值： $light \n" + "戒指语言为： ${
                        parseDeviceLanguage(
                            languageType
                        )
                    } \n" + "是否支持任务： $taskSupport \n" + "任务状态： $taskStatus \n" + "赞念目标值： $targetNumber \n" + "赞念词ID： $taskId \n" + "协议版本号： $protocolVersion "
                )

                appProtocolImpl.onDeviceConfigInfoCallback(
                    isPositive,
                    isOpenPray,
                    chartingStartTime,
                    chartingEndTime,
                    light,
                    languageType,
                    timeInterval,
                    taskSupport,
                    taskStatus,
                    targetNumber,
                    taskId,
                    remarks,
                    protocolVersion
                )
            }
            //主动停止寻找设备：设备端已停止寻找,不需要APP端反馈：R04
            "R04" -> {
                appProtocolImpl.requestStopFindDevice()
            }
            //重启：Q10
            "Q10" -> {
                appProtocolImpl.onRebootCallback()
            }
            //日志：Q14
            "Q14" -> {
                appProtocolImpl.onDeviceLogCallback()
            }
            //屏幕亮度：Q15
            "Q15" -> {
                appProtocolImpl.onDeviceScreenBrightnessCallback()
            }
            //设置多语言回调：Q16
            "Q16" -> {
                appProtocolImpl.onSettingDeviceLanguageCallback()
            }
            //特殊祈祷设置：Q17
            "Q17" -> {
                appProtocolImpl.onSettingCustomizeConventionCallback()
            }
            //设置自定义惯例：Q18
            "Q18" -> {
                appProtocolImpl.onSettingStableConventionCallback()
            }
            //赞念任务设置：Q19
            "Q19" -> {
                appProtocolImpl.onSettingTasbihTaskCallback()
            }
            //设置自定义惯例的回调：Q20
            "Q20" -> {
                val split = result.split(",")
                //目标计数值
                val targetNumber = split[1].toInt()
                //当前任务经文值
                val taskId: Int = split[2].toInt()
                //任务开始时间
                val startTime = convertDateTimeFormat(
                    split[3],
                    SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH),
                    SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
                )

                //任务结束时间
                val endTime = convertDateTimeFormat(
                    split[4],
                    SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH),
                    SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
                )

                //tick值
                val tick = split[5]

                UMRingSdk.log(
                    TAG,
                    "解析结果：\n" + "开始时间：$startTime \n" + "结束时间:$endTime \n" + "目标数量:$targetNumber \n" + "tick值:$tick \n" + "taskId:$taskId ---"
                )

                appProtocolImpl.onGetTasbihTaskInfoCallback(
                    targetNumber, taskId, startTime, endTime, tick
                )
            }
            //设置船航模式：Q21
            "Q21" -> {
                UMRingSdk.log(
                    TAG, "设置船航模式成功"
                )
                appProtocolImpl.onSetShipNavigationMode()
            }

            "Q22" -> {
                appProtocolImpl.onSetScreenRestTime()
            }

            "Q23" -> {
                appProtocolImpl.onSetPrayerRemindConfig()
            }

            "Q24" -> {
                appProtocolImpl.onSetCustomCountReminder()
            }

            "Q25" -> {
                val strList = result.split(",")
                //息屏时间
                val restTime = strList[1].toInt()
                //晨礼开关#偏移时间#提醒时间:晌礼开关#偏移时间#提醒时间:晡礼开关#偏移时间#提醒时间:昏礼开关#偏移时间#提醒时间:宵礼开关#偏移时间#提醒时间
                val configs = Array(5) {
                    Array(3) {
                        0
                    }
                }
                val prayerConfig = strList[2].split(":")
                for ((index, s) in prayerConfig.withIndex()) {
                    for ((index1, s1) in s.split("#").withIndex()) {
                        configs[index][index1] = s1.toInt()
                    }
                }

                //普通计数33*N模式开关#普通计数100*N模式开关#自定义计数值
                val countMode = strList[3].split("#")
                val normal33 = countMode[0].toInt() > 0
                val normal100 = countMode[1].toInt() > 0
                val customValue = countMode[2].toInt()

                UMRingSdk.log(
                    TAG,
                    "解析结果：\n息屏时间：$restTime \n祈祷配置:\n" + "${
                        parsePrayerConfigInfo(configs)
                    } \n" + "普通计数33*N模式开关:$normal33 \n" + "普通计数100*N模式开关:$normal100 \n" + "自定义计数值:$customValue ---"
                )

                appProtocolImpl.onGetPrayerRemindConfig(
                    restTime, configs, normal33, normal100, customValue
                )
            }

            "Q26" -> {
                appProtocolImpl.onSetUserInfo()
            }

            "Q27" -> {
                val strList = result.split(",")
                //息屏时间
                val step = strList[1].toInt()
                appProtocolImpl.onGetCurrentStep(step)
            }

            "Q30" -> {
                val strList = result.split(",")
                //息屏时间
                var pkey = ""
                if (strList.size >= 2) {
                    pkey = strList[1]
                }
                appProtocolImpl.onPkeyOperation(pkey)
            }

            "Q32" -> {
                val strList = result.split(",")
                val gsensorId = strList[1].toInt()
                val status = strList[2].toInt()
                val datas = mutableListOf<Int>()
                for (i in 3..5) {
                    val dataArr = strList[i].split("#")
                    for (s in dataArr) {
                        datas.add(s.toInt())
                    }
                }
                appProtocolImpl.onGsensorTest(gsensorId, status, datas.toTypedArray())
            }

            "Q34" -> {
                val strList = result.split(",")
                //更新时间
                val updateTime = convertDateTimeFormat(
                    strList[1],
                    SimpleDateFormat("yyyyMMddHHmm", Locale.ENGLISH),
                    SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
                )
                val countSplit = strList[2].split("#")
                val fajrCount: Int = countSplit[0].toInt()
                val dhuhrCount: Int = countSplit[1].toInt()
                val asrCount: Int = countSplit[2].toInt()
                val maghribCount: Int = countSplit[3].toInt()
                val ishaCount: Int = countSplit[4].toInt()
                val tick: String = strList[3]
                val endFlag: Int = strList[4].toInt()

                appProtocolImpl.onGetWorshipCacheData(
                    updateTime,
                    fajrCount,
                    dhuhrCount,
                    asrCount,
                    maghribCount,
                    ishaCount,
                    tick,
                    endFlag
                )
            }

            "Q35" -> {
                val strList = result.split(",")
                val count = strList[1].toInt()
                appProtocolImpl.onGetRealtimeWorship(count)
            }

            "Q36" -> {
                appProtocolImpl.onSetLedTimeAndLight()
            }

            "Q37" -> {
                val strList = result.split(",")
                val battery = strList[3].toInt()
                val lightTime = strList[4].toInt()
                val light = strList[5].toInt()
                val protocolVersion = strList[6]
                var softwareVersion = ""
                if (strList.size >= 8) {
                    softwareVersion = strList[7]
                }
                var audioEnable = false
                if (strList.size >= 9) {
                    audioEnable = (strList[8].toIntOrNull() == 1)
                }
                appProtocolImpl.onGetSc01DeviceInfo(
                    battery,
                    lightTime,
                    light,
                    protocolVersion,
                    softwareVersion,
                    audioEnable
                )
            }

            "Q38" -> {
                val strList = result.split(",")
                val enable = strList[1].toInt() == 0
                appProtocolImpl.onDeviceInfraRedTest(enable)
            }

            "Q39" -> {
//                val strList = result.split(",")
                appProtocolImpl.onDeviceRadarTest(true)
            }

            "Q40" -> {
                val strList = result.split(",")
                val cacheCount = strList[1].toInt()
                appProtocolImpl.onGetAllWorshipCacheData(cacheCount)
            }

            "Q41" -> {
                val strList = result.split(",")
                val success = strList[1].toInt() == 1
                appProtocolImpl.onModifyWorshipNumberByIndex(success)
            }

            "Q42" -> {
                val strList = result.split(",")
                val enable = strList[1].toInt() == 0
                appProtocolImpl.onDeviceMotorAgingTest(enable)
            }

            "Q43" -> {
                appProtocolImpl.onGetDeviceMotorAgingTestResul()
            }

            "Q44" -> {
                val strList = result.split(",")
                val status = strList[1].toInt()
                val distance = strList[2].toInt()
                appProtocolImpl.onGetTofResult(status, distance)
            }

            "Q45" -> {
                val strList = result.split(",")
                val status = strList[1].toInt()
                appProtocolImpl.onTofCalibration1(status)
            }

            "Q46" -> {
                val strList = result.split(",")
                val status = strList[1].toInt()
                appProtocolImpl.onTofCalibration1(status)
            }

            "Q47" -> {
                appProtocolImpl.onSc01SpeakerAudioTest()
            }

            "Q50" -> {
                val strList = result.split(",")
                //日期时间
                val datetime = strList[1].substring(0, strList[1].length - 1)
                val packageIndex = strList[1].substring(strList[1].length - 1).toIntOrNull() ?: -1

                val datas = mutableListOf<String>()
                if (packageIndex < 4) {
                    val split = strList[2].substring(0, strList[2].length - 1).split("#")
                    for (s in split) {
                        datas.add(s)
                    }
                } else {
                    datas.add(strList[2])
                    datas.add(strList[3])
                    datas.add(strList[4])
                }

                UMRingSdk.log(
                    TAG,
                    "解析结果：\n" + "日期时间：$datetime \n" + "包下标:$packageIndex\n" + "数据：${datas.joinToString()}---"
                )

                appProtocolImpl.onGSensorDataReport(
                    datetime, packageIndex, datas.toTypedArray()
                )
            }

            "Q51" -> {
                appProtocolImpl.onSetSc01AudioEnable()
            }
        }
    }

    /**
     * 转换时间格式
     * 如：dateTime  20220624145912    parseDateFormat  yyyyMMddHHmmss   formatDateFormat yyyy-MM-dd HH:mm:ss
     * 得到的结果为：2022-06-24 14：59：12
     * 如果传入的格式解析失败  则会返回 “”字符
     */
    private fun convertDateTimeFormat(
        dateTime: String, parseDateFormat: SimpleDateFormat, formatDateFormat: SimpleDateFormat
    ): String {
        val parseDate = parseDateFormat.parse(dateTime)
        return if (parseDate != null) {
            return formatDateFormat.format(parseDate)
        } else {
            ""
        }
    }

    /**
     * 晨礼开关#偏移时间#提醒时间:晌礼开关#偏移时间#提醒时间:晡礼开关#偏移时间#提醒时间:昏礼开关#偏移时间#提醒时间:宵礼开关#偏移时间#提醒时间
     */
    private fun parsePrayerConfigInfo(configs: Array<Array<Int>>): String {
        val sb = StringBuilder()
        sb.append("晨礼开关:${configs[0][0] > 0}")
        sb.append("偏移时间:${configs[0][1]}")
        sb.append("提醒时间:${configs[0][2]}\n")
        sb.append("晌礼开关:${configs[1][0] > 0}")
        sb.append("偏移时间:${configs[1][1]}")
        sb.append("提醒时间:${configs[1][2]}\n")
        sb.append("晡礼开关:${configs[2][0] > 0}")
        sb.append("偏移时间:${configs[2][1]}")
        sb.append("提醒时间:${configs[2][2]}\n")
        sb.append("昏礼开关:${configs[3][0] > 0}")
        sb.append("偏移时间:${configs[3][1]}")
        sb.append("提醒时间:${configs[3][2]}\n")
        sb.append("宵礼开关:${configs[4][0] > 0}")
        sb.append("偏移时间:${configs[4][1]}")
        sb.append("提醒时间:${configs[4][2]}")
        return sb.toString()
    }

    /**
     * 解析赞念提醒状态
     */
    private fun parseDhikrRemindStatus(timeInterval: Int) = when (timeInterval) {
        0 -> "关闭"
        else -> "开启"
    }

    /**
     * 解析礼拜提醒状态
     */
    private fun parseSalahRemindStatus(openPray: Int) = when (openPray) {
        0 -> "关闭"
        1 -> "开启"
        else -> "未知状态"
    }

    /**
     * 解析屏幕翻转状态
     * 0:正；1:反
     */
    private fun parsePositive(positive: Boolean): String = if (positive) {
        "正面"
    } else {
        "反面"
    }

    /**
     * 解析设备电池状态
     * 0：未充电；1：充电；2：充满 3：低电
     */
    private fun parseBatteryStatus(status: String) = when (status) {
        "0" -> "未充电"
        "1" -> "充电中"
        "2" -> "已充满"
        "3" -> "低电量"
        else -> "未知状态"
    }

}